﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.Objects;

namespace XBoshiGFS.forms
{
    public partial class MainForm : Form
    {
     
        private StationSet  currentStation=null;
        private SegmentCourseSet  currentSegment = null;
        private VillageSet  currentVillage = null;
        private GroupSet  currentGroup = null;
        private WaterCourseSet currentWaterCourse = null;


        ContextMenuStrip VillageMenu = new ContextMenuStrip();
        ContextMenuStrip GroupMenu = new ContextMenuStrip();
        ContextMenuStrip SegmentMenu = new ContextMenuStrip();
        ContextMenuStrip WaterCourseMenu = new ContextMenuStrip();
        ContextMenuStrip StationMenu = new ContextMenuStrip();

        private XBoshiGFSModelContainer _context = new XBoshiGFSModelContainer();



        public MainForm()
        {
            InitializeComponent();


            //构建右键菜单
            BuilderPopUpMenu(null);
            //构建树
            BuilderStationTree();

  

        }
        /// <summary>
        /// 构建站下的所有支渠
        /// </summary>
        /// <param name="station"></param>
        /// <param name="tn"></param>
        private void BuilderSegmentTree(StationSet station,TreeNode tn)
        {
            var container = _context;
            tn.Nodes.Clear();
            station.SegmentCourseSet.Load(MergeOption.PreserveChanges);  
             foreach (var seg in station.SegmentCourseSet)
                {
                    TreeNode ts = new TreeNode();
                    ts.Text = seg.strName;
                    ts.Tag = seg;
                    ts.ContextMenuStrip = SegmentMenu;
                    tn.Nodes.Add(ts);
                 //下面的所有斗渠
                    BuilderWaterCourseTree(seg, ts);
                }


        }



        /// <summary>
        /// 构建支渠下的所有斗渠
        /// </summary>
        /// <param name="segment"></param>
        /// <param name="tn"></param>
        private void BuilderWaterCourseTree(SegmentCourseSet   segment, TreeNode tn)
        {
            var container = _context;
            tn.Nodes.Clear();
            segment.WaterCourseSet.Load(MergeOption.PreserveChanges);  
            foreach (var seg in segment.WaterCourseSet )
            {
                TreeNode ts = new TreeNode();
                ts.Text = seg.strName;
                ts.Tag = seg;
                ts.ContextMenuStrip = WaterCourseMenu;
                tn.Nodes.Add(ts);
                //下面的所有村
                BuilderVillageTree(seg, ts);

            }


        }
        /// <summary>
        /// 构建斗渠下的所有村
        /// </summary>
        /// <param name="segment"></param>
        /// <param name="tn"></param>
        private void BuilderVillageTree(WaterCourseSet  water, TreeNode tn)
        {
            var container = _context;
            tn.Nodes.Clear();
            water.VillageSet.Load(MergeOption.PreserveChanges);
            foreach (var seg in water.VillageSet)
            {
                TreeNode ts = new TreeNode();
                ts.Text = seg.strName;
                ts.Tag = seg;
                ts.ContextMenuStrip = WaterCourseMenu;
                tn.Nodes.Add(ts);
                //下面的所有组
                BuilderGroupTree(seg, ts);
            }
        }
        /// <summary>
        /// 构建村下的所有租
        /// </summary>
        /// <param name="water"></param>
        /// <param name="tn"></param>
        private void BuilderGroupTree(VillageSet  village, TreeNode tn)
        {
            tn.Nodes.Clear();
            village.GroupSet.Load(MergeOption.PreserveChanges);
            foreach (var seg in village.GroupSet )
            {
                TreeNode ts = new TreeNode();
                ts.Text = seg.strName;
                ts.Tag = seg;
                ts.ContextMenuStrip = WaterCourseMenu;
                tn.Nodes.Add(ts);
            }
        }
        
        
        /// <summary>
        /// 构建所有的站
        /// </summary>
        private void BuilderStationTree() {
                var container = _context;
                OrgTreeView.Nodes.Clear() ;

                var sts = (from p in container.StationSet select p)  ;
                
                foreach (var st in sts )
                {
                    TreeNode tn = new TreeNode();
                    tn.Text = st.strName;
                    tn.Tag = st;
                    tn.ContextMenuStrip = StationMenu;
                    BuilderSegmentTree(st, tn);
                    OrgTreeView.Nodes.Add(tn);
             }

                if (OrgTreeView.Nodes.Count > 0)
                {
                    OrgTreeView.Nodes[0].Expand();
                }
        }


        private void OrgTreeView_AfterSelect(object sender, TreeViewEventArgs e)
        {
            var tn = e.Node;
            if (tn.Tag is StationSet) {
                currentStation = (StationSet)tn.Tag;
            }

            if (tn.Tag is SegmentCourseSet)
            {
                currentSegment  = (SegmentCourseSet)tn.Tag;
                currentStation = currentSegment.StationSet;
            }
            if (tn.Tag is WaterCourseSet )
            {
                currentWaterCourse = (WaterCourseSet)tn.Tag;
                currentSegment = currentWaterCourse.SegmentCourseSet;
                currentStation = currentSegment.StationSet;
            }


            if (tn.Tag is VillageSet )
            {
                currentVillage= (VillageSet )tn.Tag;
                currentWaterCourse = currentVillage.WaterCourseSet;
                currentSegment = currentWaterCourse.SegmentCourseSet;
                currentStation = currentSegment.StationSet;
            }

            if (tn.Tag is GroupSet )
            {
                currentGroup = (GroupSet )tn.Tag;
                currentVillage = currentGroup.VillageSet;
                currentWaterCourse = currentVillage.WaterCourseSet;
                currentSegment = currentWaterCourse.SegmentCourseSet;
                currentStation = currentSegment.StationSet; 


            }


        }

        private void OrgTreeView_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                //右键，弹出菜单
                TreeNode tn = ((TreeView)sender).SelectedNode;
                tn.ContextMenuStrip = GetMenuStrip(tn.Tag);

            }
            else { 
                //如果是组节点，则展现该组下所有的用户
                this.Cursor = Cursors.WaitCursor; 
                TreeNode tn = ((TreeView)sender).SelectedNode;
                if (tn.Tag is GroupSet) { 
                    GroupSet group =(GroupSet )tn.Tag ;
                    QueryUserListData(group );
                }
                this.Cursor = Cursors.Default ;
            }    
        }

        //private void OrgTreeView_MouseClick(object sender, MouseEventArgs e)
        //{
        //    if (e.Button == MouseButtons.Right)
        //    {
        //        //右键，弹出菜单
        //        TreeNode tn = ((TreeView)sender).SelectedNode;
        //        tn.ContextMenuStrip = GetMenuStrip(tn.Tag);
                
        //    }    
        //}

        private void MainForm_Load(object sender, EventArgs e)
        {
            //构建菜单树
             




        }


        private ContextMenuStrip GetMenuStrip(object NodeTag)
        {

            if (NodeTag is SegmentCourseSet)
            {

                SegmentMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
                        this.MNU_ModifySegment,
                        this.MNU_DeleteSegment,
                        this.toolStripMenuItem1,
                        this.MNU_AddWaterCourse,
                        this.toolStripMenuItem1,
                        this.MNU_Refresh 

            }
                    );
                return SegmentMenu;
            }
            else if (NodeTag is WaterCourseSet )
            {
                WaterCourseMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
                        this.MNU_ModifyWaterCourse,
                        this.MNU_DeleteCursor,
                        this.toolStripMenuItem1,
                        this.MNU_AddVillage,
                        this.toolStripMenuItem1,
                        this.MNU_Refresh 
                        }
                    );
                return WaterCourseMenu;
            }
            else if (NodeTag is VillageSet)
            {
                VillageMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
                    this.MNU_ModifyVillage,
                    this.MNU_DeleteVillage,
                    this.toolStripMenuItem3,
                    this.MNU_AddGroup,
                        this.toolStripMenuItem1,
                        this.MNU_Refresh 
                }
                    );
                return VillageMenu;
            }
            else if (NodeTag is GroupSet)
            {
                GroupMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
                    this.MNU_ModifyGroup,
                    this.MNU_DeleteGroup,
                        this.toolStripMenuItem1,
                        this.MNU_Refresh 
                }
                    );
                return GroupMenu;
            }
            else if (NodeTag is StationSet)
            {
                StationMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
                        this.MNU_AddSegment ,
                        this.toolStripMenuItem2,
                        this.MNU_Refresh ,
                        this.MNU_PriceMaintain,
                        this.toolStripMenuItem1,
                        this.MNU_Refresh 

            }
                    );
                return StationMenu;
            }
            //else if (NodeTag == null)
            //{

            //    StationMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
            //            this.MNU_AddSegment ,
            //            this.toolStripMenuItem2,
            //            this.MNU_Refresh ,
            //            this.MNU_PriceMaintain,
            //            this.toolStripMenuItem1,
            //            this.MNU_Refresh 

            //}
            //        );
            //    return StationMenu;
            //}
            else {
                return null;
            
            }
       
        }




        private void BuilderPopUpMenu(object NodeTag)
        {
            SegmentMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
                        this.MNU_ModifySegment,
                        this.MNU_DeleteSegment,
                        this.toolStripMenuItem1,
                        this.MNU_AddWaterCourse,
                        this.toolStripMenuItem2,
                        this.MNU_Refresh 

            }
                );
            WaterCourseMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
                        this.MNU_ModifyWaterCourse,
                        this.MNU_DeleteCursor,
                        this.toolStripMenuItem1,
                        this.MNU_AddVillage,
                        this.toolStripMenuItem2,
                        this.MNU_Refresh 
                        }
                );

                VillageMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
                    this.MNU_ModifyVillage,
                    this.MNU_DeleteVillage,
                    this.toolStripMenuItem1,
                    this.MNU_AddGroup,
                        this.toolStripMenuItem2,
                        this.MNU_Refresh 
                }
                    );

                GroupMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
                    this.MNU_ModifyGroup,
                    this.MNU_DeleteGroup,
                        this.toolStripMenuItem1,
                        this.MNU_Refresh 
                }
                    );
                StationMenu.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
                        this.MNU_AddSegment ,
                        this.toolStripMenuItem1,
                        this.MNU_Refresh 

            }
                    );
        }

        private void AddSegment_Click(object sender, EventArgs e)
        {
            StationSet station = currentStation;
            SegmentForm sm = new SegmentForm(station);
            sm.FormClosed += new FormClosedEventHandler(sm_FormClosed);
            sm.ShowDialog();

        }
        

        private void MNU_AddStation_Click(object sender, EventArgs e)
        {
 
            StationForm sm = new StationForm();
            sm.FormClosed += new FormClosedEventHandler(sm_FormClosed);
            sm.ShowDialog();

        }

        /// <summary>
        /// 刷新指定节点
        /// </summary>
        /// <param name="NodeType"></param>
        /// <param name="tn"></param>
        private void RefreshTree(object NodeType, TreeNode tn) {
            //清除当前节点
            tn.Nodes.Clear();   
            
            //构建下面的子节点
            if (tn.Tag is StationSet) {
                BuilderSegmentTree((StationSet)tn.Tag, tn);

            } if (tn.Tag is SegmentCourseSet) {
                BuilderWaterCourseTree((SegmentCourseSet)tn.Tag, tn);
            } if (tn.Tag is WaterCourseSet)
            {
                BuilderVillageTree((WaterCourseSet)tn.Tag, tn);

            } if (tn.Tag is VillageSet) {
                BuilderGroupTree((VillageSet)tn.Tag, tn);
            }
            tn.Expand(); 
        }

        private void ORG_Tree_Refresh()
        {
            _context = new XBoshiGFSModelContainer();


            TreeNode tn = OrgTreeView.SelectedNode;
            if (tn == null)
            {
                tn = OrgTreeView.Nodes[0];

            }
            else
            {
                tn = tn.Parent;
            }
            if (tn == null)
            {
                tn = OrgTreeView.Nodes[0];
            }

            RefreshTree(tn.Tag, tn);
            
            tn.Expand();
        }


        private void MNU_ModifySegment_Click(object sender, EventArgs e)
        {

            SegmentCourseSet sg = currentSegment;
            SegmentForm sm = new SegmentForm(sg);
            sm.FormClosed += new FormClosedEventHandler(sm_FormClosed);
            sm.ShowDialog();
            
        }

        private void MNU_AddVillage_Click(object sender, EventArgs e)
        {

            WaterCourseSet  waterCursor = currentWaterCourse;
            VillageForm sm = new VillageForm(waterCursor);
            sm.FormClosed += new FormClosedEventHandler(sm_FormClosed);
            sm.ShowDialog();

        }

        private void MNU_AddWaterCourse_Click(object sender, EventArgs e)
        {

            SegmentCourseSet segment = currentSegment;
            WaterCourseForm sm = new WaterCourseForm(segment);
            sm.FormClosed += new FormClosedEventHandler(sm_FormClosed);
            sm.ShowDialog();
        }

        private void MNU_AddGroup_Click(object sender, EventArgs e)
        {
            VillageSet village = currentVillage;
            GroupForm sm = new GroupForm(village);
            sm.FormClosed += new FormClosedEventHandler(sm_FormClosed);
            sm.ShowDialog();



        }

        private void MNU_ModifyWaterCourse_Click(object sender, EventArgs e)
        {
            WaterCourseSet wcs = currentWaterCourse;
            WaterCourseForm sm = new WaterCourseForm(wcs);
            sm.FormClosed += new FormClosedEventHandler(sm_FormClosed);
            sm.ShowDialog();
       }


        void sm_FormClosed(object sender, FormClosedEventArgs e)
        {
            //窗口关闭后，刷新数据   

            ORG_Tree_Refresh(); 
        }

        private void MNU_ModifyVillage_Click(object sender, EventArgs e)
        {


            VillageSet village = currentVillage ;
            VillageForm sm = new VillageForm(village);
            sm.FormClosed += new FormClosedEventHandler(sm_FormClosed);
            sm.ShowDialog();


        }

        private void MNU_ModifyGroup_Click(object sender, EventArgs e)
        {
            GroupSet group = currentGroup ;
            GroupForm sm = new GroupForm(group);
            sm.FormClosed += new FormClosedEventHandler(sm_FormClosed);
            sm.ShowDialog();
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            GroupSet groupset = currentGroup;
            if (groupset == null) {

                return;
            }
            peopleSetBindingSource.Clear(); 
            peopleSetBindingSource.DataSource = null;
            _context.PeopleSet.MergeOption = MergeOption.OverwriteChanges;    
            var varlist = (from p in _context.PeopleSet where p.GroupId == groupset.Id select p);
              
            peopleSetBindingSource.DataSource = varlist.ToList();
        }


        public void QueryUserListData( GroupSet  groupset) {
            using (XBoshiGFSModelContainer ctx = new XBoshiGFSModelContainer())
            {
                var varlist = (from p in ctx.PeopleSet where p.GroupId == groupset.Id select p);
                peopleSetBindingSource.DataSource = varlist.ToList();
            }
  
                //var varlist = (from p in _context.PeopleSet where p.GroupId == groupset.Id select p);
                //peopleSetBindingSource.DataSource = varlist.ToList();
 
        
        }

        private void btnNew_Click(object sender, EventArgs e)
        {
            PeopleForm pm = new PeopleForm( );
            pm.FormClosed += new FormClosedEventHandler(pm_FormClosed);
            pm.ShowDialog(); 
 
        }

        private void dataGridView2_CellContentDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
 
            BindingSource bins=(BindingSource)dataGridView2.DataSource;
            PeopleSet people = (PeopleSet)bins.Current;
            PeopleForm pm = new PeopleForm(people);
            pm.FormClosed += new FormClosedEventHandler(pm_FormClosed);
            pm.ShowDialog(); 

        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            _context.SaveChanges(); 
        }

        private void MNU_PriceMaintain_Click(object sender, EventArgs e)
        {
            PriceMaintainForm pm = new PriceMaintainForm(MainMDIParent.station );
            pm.ShowDialog(); 
        }



        private void MNU_Refresh_Click(object sender, EventArgs e)
        {
            TreeNode tn = OrgTreeView.SelectedNode;
            if (tn == null)
            {
                tn = OrgTreeView.Nodes[0];

            }
            else {
                tn = tn.Parent; 
            }
            if (tn == null)
            {
                tn = OrgTreeView.Nodes[0];
            }

            _context = new XBoshiGFSModelContainer();
            RefreshTree(tn.Tag, tn);
            tn.Expand();

            
        }

        private void btnModify_Click(object sender, EventArgs e)
        {
            BindingSource bins = (BindingSource)dataGridView2.DataSource;
            PeopleSet people = (PeopleSet)bins.Current;
            if (people == null) {
                return  ;
            }
            PeopleForm pm = new PeopleForm(people);
            pm.FormClosed += new FormClosedEventHandler(pm_FormClosed);
            pm.ShowDialog();
        }

        void pm_FormClosed(object sender, FormClosedEventArgs e)
        {
            //修改界面窗口关闭后，刷新数据
            btnRefresh_Click(null,null);
           
        }

        private void OrgTreeView_MouseClick(object sender, MouseEventArgs e)
        {

        }

        private void OrgTreeView_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetDataPresent("System.Windows.Forms.TreeNode"))
            {
                e.Effect = DragDropEffects.Move;
            }
            else
            {
                e.Effect = DragDropEffects.None;
            }
        }

        private void OrgTreeView_DragDrop(object sender, DragEventArgs e)
        {
            try
            {
                //获得拖放中的节点
                TreeNode moveNode = (TreeNode)e.Data.GetData("System.Windows.Forms.TreeNode");
                //根据鼠标坐标确定要移动到的目标节点
                Point pt;
                TreeNode targeNode;
                pt = ((TreeView)(sender)).PointToClient(new Point(e.X, e.Y));
                targeNode = this.OrgTreeView.GetNodeAt(pt);

               // 目标节点为空时，停止操作
                if (targeNode == null) return;
                // 去除本身拖放的情况
                if (targeNode == moveNode) return;
                // 防止拖放到自己的子级当中
                //if (ChildJudge(targeNode, moveNode)) return;

                int index = moveNode.Tag.ToString().IndexOf(",");

                //检查拖动关系，组只能拖到上一个级别下
                if(moveNode.Tag is GroupSet && !(targeNode.Tag  is VillageSet) ) return ;
                if(moveNode.Tag is VillageSet && !(targeNode.Tag is WaterCourseSet) ) return ;
                if(moveNode.Tag is WaterCourseSet && !(targeNode.Tag is SegmentCourseSet) ) return ;
                if(moveNode.Tag is SegmentCourseSet && !(targeNode.Tag is StationSet) ) return ;



                if (moveNode.Tag is GroupSet) { 
                    //拖动的是组，将调整组的村关系
                    GroupSet g = (GroupSet)moveNode.Tag;
                    g.VillageSet = (VillageSet)targeNode.Tag; 
                }
                if (moveNode.Tag is VillageSet)
                {
                    //拖动的是组，将调整村的村关系
                    VillageSet g = (VillageSet)moveNode.Tag;
                    g.WaterCourseSet = (WaterCourseSet)targeNode.Tag;
                }
                if (moveNode.Tag is WaterCourseSet)
                {
                    //拖动的是组，将调整村的村关系
                    WaterCourseSet g = (WaterCourseSet)moveNode.Tag;
                    g.SegmentCourseSet  = (SegmentCourseSet)targeNode.Tag;
                }
                if (moveNode.Tag is SegmentCourseSet)
                {
                    //拖动的是组，将调整村的村关系
                    SegmentCourseSet g = (SegmentCourseSet)moveNode.Tag;
                    g.StationSet  = (StationSet)targeNode.Tag;
                }

                _context.SaveChanges();
                ORG_Tree_Refresh();
               
            }
            catch (Exception ex)
            {
                //log.Error(Definition.MESSAGE_QUERY_ERROR + ":" + ex.Message);
                //Tool.ShowMessage(Definition.MESSAGE_QUERY_ERROR + ":" + ex.Message, MessageBoxIcon.Error);
            }

        }

        private void OrgTreeView_ItemDrag(object sender, ItemDragEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                DoDragDrop(e.Item, DragDropEffects.Move);
            }
        }



    }
}
